-- ============================================
-- ROULETTE VISUELLE - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local RED_NUMBERS = {
    [1]=true,[3]=true,[5]=true,[7]=true,[9]=true,[12]=true,[14]=true,[16]=true,
    [18]=true,[19]=true,[21]=true,[23]=true,[25]=true,[27]=true,[30]=true,[32]=true,
    [34]=true,[36]=true,
}

-- Ordre reel des numeros sur une roue europeenne (pour l'animation de la bille)
local WHEEL_ORDER = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,
                      16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26}

local function colorOf(n)
    if n == 0 then return colors.green end
    if RED_NUMBERS[n] then return colors.red end
    return colors.gray -- "noir" affiche en gris pour rester visible sur fond noir
end

local MISE = 1
local points = 100
local betType = nil   -- "number" ou "color"
local betValue = nil  -- numero ou couleur choisie

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

-- === CONSTRUCTION DE LA GRILLE ===
local cellW = 4   -- largeur de chaque case
local cellH = 3   -- hauteur de chaque case
local gridTop = 5
local totalGridWidth = cellW * 13  -- case "0" + 12 colonnes
local gridStartX = math.max(1, math.floor((w - totalGridWidth) / 2) + 1)
local cellPos = {}  -- cellPos[number] = {x1, x2, y1, y2}

local function drawCell(n, x1, x2, y1, y2, highlight)
    local bg = colorOf(n)
    if highlight then
        term.setBackgroundColor(colors.white)
        term.setTextColor(colors.black)
    else
        term.setBackgroundColor(bg)
        term.setTextColor(colors.white)
    end
    for y = y1, y2 do
        for x = x1, x2 do
            term.setCursorPos(x, y)
            term.write(" ")
        end
    end
    local label = tostring(n)
    local lx = x1 + math.floor(((x2 - x1 + 1) - #label) / 2)
    local ly = y1 + math.floor((y2 - y1) / 2)
    term.setCursorPos(lx, ly)
    term.write(label)
end

local function drawGrid(highlightNumber)
    -- case 0 a gauche, sur toute la hauteur des 3 rangees
    local zx1, zx2 = gridStartX, gridStartX + cellW - 1
    local zy1, zy2 = gridTop, gridTop + cellH * 3 - 1
    drawCell(0, zx1, zx2, zy1, zy2, highlightNumber == 0)
    cellPos[0] = { x1 = zx1, x2 = zx2, y1 = zy1, y2 = zy2 }

    for col = 1, 12 do
        local x1 = gridStartX + cellW + (col - 1) * cellW
        local x2 = x1 + cellW - 1
        local topNum = col * 3
        local midNum = col * 3 - 1
        local botNum = col * 3 - 2

        local topY1, topY2 = gridTop, gridTop + cellH - 1
        local midY1, midY2 = topY2 + 1, topY2 + cellH
        local botY1, botY2 = midY2 + 1, midY2 + cellH

        drawCell(topNum, x1, x2, topY1, topY2, highlightNumber == topNum)
        drawCell(midNum, x1, x2, midY1, midY2, highlightNumber == midNum)
        drawCell(botNum, x1, x2, botY1, botY2, highlightNumber == botNum)

        cellPos[topNum] = { x1 = x1, x2 = x2, y1 = topY1, y2 = topY2 }
        cellPos[midNum] = { x1 = x1, x2 = x2, y1 = midY1, y2 = midY2 }
        cellPos[botNum] = { x1 = x1, x2 = x2, y1 = botY1, y2 = botY2 }
    end
end

local gridBottom = gridTop + cellH * 3 - 1

-- Boutons de mise exterieure (rouge / noir / vert) sous la grille
local outsideButtons = {}
local function drawOutsideBets(selected)
    local labels = { "ROUGE", "NOIR", "VERT" }
    local cols = { colors.red, colors.gray, colors.green }
    local y = gridBottom + 2
    local btnW = math.floor(w / 3)
    outsideButtons = {}
    for i = 1, 3 do
        local x1 = (i - 1) * btnW + 1
        local x2 = x1 + btnW - 1
        term.setBackgroundColor(selected == i and colors.white or cols[i])
        term.setTextColor(selected == i and colors.black or colors.white)
        for x = x1, x2 do
            term.setCursorPos(x, y)
            term.write(" ")
        end
        local lx = x1 + math.floor((btnW - #labels[i]) / 2)
        term.setCursorPos(lx, y)
        term.write(labels[i])
        outsideButtons[i] = { x1 = x1, x2 = x2, y = y, name = labels[i] }
    end
end

local function drawFrame(message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "ROULETTE", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    drawGrid(nil)
    drawOutsideBets(nil)
    local msgY = gridBottom + 4
    if message then
        centerText(msgY, message, msgColor or colors.white)
    end
    centerText(h, "Touche un numero OU une couleur pour miser", colors.lightGray)
end

-- Anime la bille qui tourne sur la roue en parcourant WHEEL_ORDER
local function spinBall()
    local startIdx = math.random(1, #WHEEL_ORDER)
    local steps = 28 + math.random(0, 8)
    local finalNumber

    for step = 1, steps do
        local idx = ((startIdx + step - 2) % #WHEEL_ORDER) + 1
        local n = WHEEL_ORDER[idx]
        drawGrid(n)
        centerText(gridBottom + 4, "La bille tourne...", colors.yellow)
        finalNumber = n
        sleep(0.03 + (step / steps) * 0.12) -- ralentit progressivement
    end

    return finalNumber
end

local function payout(number)
    if betType == "number" then
        if betValue == number then return MISE * 35 end
        return 0
    elseif betType == "color" then
        local resultColorName
        if number == 0 then resultColorName = "VERT"
        elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
        else resultColorName = "NOIR" end

        if betValue == resultColorName then
            if resultColorName == "VERT" then return MISE * 14 end
            return MISE * 2
        end
        return 0
    end
    return 0
end

local function playRound()
    if points < MISE then
        drawFrame("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    if not betType then
        drawFrame("Choisis d'abord une mise !", colors.orange)
        sleep(1.5)
        return
    end

    points = points - MISE
    drawFrame("Mise placee, la roue tourne...", colors.yellow)
    sleep(0.4)

    local number = spinBall()
    local gain = payout(number)
    points = points + gain

    local resultColorName
    if number == 0 then resultColorName = "VERT"
    elseif RED_NUMBERS[number] then resultColorName = "ROUGE"
    else resultColorName = "NOIR" end

    drawGrid(number)
    local msg = "Resultat : " .. number .. " (" .. resultColorName .. ")"
    centerText(gridBottom + 4, msg, colors.white)
    if gain > 0 then
        centerText(gridBottom + 5, "GAGNE ! +" .. gain, colors.lime)
    else
        centerText(gridBottom + 5, "Perdu... reessaie !", colors.red)
    end
    sleep(2.5)

    betType, betValue = nil, nil
end

-- === PROGRAMME PRINCIPAL ===
drawFrame()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")

    -- clic sur un numero de la grille -> mise pleine (x35)
    local clickedNumber = nil
    for n, pos in pairs(cellPos) do
        if x >= pos.x1 and x <= pos.x2 and y >= pos.y1 and y <= pos.y2 then
            clickedNumber = n
            break
        end
    end

    if clickedNumber ~= nil then
        betType, betValue = "number", clickedNumber
        drawFrame("Mise sur le " .. clickedNumber .. " (x35)", colors.yellow)
        drawGrid(clickedNumber)
        sleep(0.6)
        playRound()
        drawFrame()
    else
        for i, btn in pairs(outsideButtons) do
            if x >= btn.x1 and x <= btn.x2 and y == btn.y then
                betType, betValue = "color", btn.name
                drawFrame("Mise sur " .. btn.name .. " (x2 ou x14)", colors.yellow)
                drawOutsideBets(i)
                sleep(0.6)
                playRound()
                drawFrame()
                break
            end
        end
    end
end